import type { PaginationProps } from 'ant-design-vue';
import { reactive,watch,toRefs,computed } from 'vue';
import type {TableStateProps,TableSource,Pageable} from "./types"
export interface Props {
  [key: string]: any;
}

function useTable (
  initParams: object = {},
  isPageable:  object | boolean = true,
  locale
){

  const state = reactive<TableStateProps>({
    tableData: [],
    searchShow: true,
    pageable: {
      current: 1,
      defaultPageSize: 20,
      hideOnSinglePage: false,
      pageSize: 20,
      pageSizeOptions: ['20', '50', '100'],
      total: 1,
      showTotal: (total) => `共 ${total} 条`,
    },
    loading: false,
    tableSize: 'middle',
    searchParam: {},
    searchInitParam: {},
    totalParam: {},
  });

  watch(
    locale,
    () => {
      if (locale.value === 'ch') {
        state.pageable.showTotal = (total) => `共 ${total} 条`;
      } else {
        state.pageable.showTotal = (total) => `Total ${total} items`;
      }
    },
    { deep: true, immediate: true }
  );

  /**
   * @description 分页查询参数(只包括分页和表格字段排序,其他排序方式可自行配置)
   * */

  const pageParam = computed({
    get: () => ({
      page: state.pageable.current,
      limit: state.pageable.pageSize,
    }),
    set: (newVal: any) => {
      console.log('我是分页更新后的值', newVal);
    },
  });

  const onLoad = () => {
    try {
      Object.assign(
        state.totalParam,
        initParams,
        isPageable ? pageParam.value : {}
      );

      state.loading = true;
    } catch (error) {
      console.log(error);
    }
  };

  /**
   * @description 更新分页信息
   * @param {Object} resPageable 后台返回的分页数据
   * @return void
   * */

  const updatePageable = (resPageable: Pageable) => {
    Object.assign(state.pageable, resPageable);
    state.loading = false;
  };

    /**
   * 更新表格数据
   * @param data 表格数据 分页时传入 current pageSize total 不分页直接传入数据数组
   */

     const updateTableData = (data: TableSource) => {
      state.tableData =
        isPageable || Reflect.has(data, 'list') ? data.list : data;
  
      const { current, pageSize, total } = data;
  
  
      if(isPageable){
        updatePageable({ current, pageSize, total });
      }
      // console.log('表格数据',state.tableData);
      
      state.loading = false;
    };

  /**
   * @description 更新查询参数
   * @return void
   * */
  const updatedTotalParam = () => {
    state.totalParam = {};
    const newSearchParams: { [propName: string]: any } = {};
    // eslint-disable-next-line no-restricted-syntax
    for (const key in state.searchParam) {
      if (
        state.searchParam[key] ||
        state.searchParam[key] === false ||
        state.searchParam[key] === 0
      ) {
        newSearchParams[key] = state.searchParam[key];
      }
    }

    Object.assign(
      state.totalParam,
      state.searchShow ? newSearchParams : {},
      isPageable ? pageParam.value : {}
    );
  };

  /**
   * @description 表格数据重置
   * @return void
   * */

  const reset = () => {
    state.pageable.current = 1;
    state.searchParam = {};
    Object.keys(state.searchInitParam).forEach((key) => {
      state.searchParam[key] = state.searchInitParam[key];
    });

    updatedTotalParam();
  };

  // 给指定的key设置value值
  const setValueByKey = (key: string, value: any) => {
    state.searchParam[key] = value;
  };

  const getsearchParam = () => state.searchParam;

  const changeTable = (pagination: PaginationProps) => {
    if (pagination.current) state.pageable.current = pagination.current;
    if (pagination.pageSize) state.pageable.pageSize = pagination.pageSize;
  };

  /**
   * @description 表格数据查询
   * @return void
   * */

  const search = (current?: number) => {
    if (current) state.pageable.current = current;
    updatedTotalParam();
  };

  /**
   *
   * @param param0 设置表格紧凑类型 key 支持 default middle small
   */
  const setTableSize = ({ key }: { key: string }) => {
    if (key) state.tableSize = key;
  };

  const toogleSearchShow = () => {
    state.searchShow = !state.searchShow;
  };

  return {
    ...toRefs(state),
    search,
    reset,
    changeTable,
    setTableSize,
    updateTableData,
    onLoad,
    toogleSearchShow,
    setValueByKey,
    getsearchParam,
  }
}

export default useTable;


